import json
import random
from pathlib import Path
from dataclasses import dataclass
from typing import NamedTuple, Dict, Literal, Tuple, cast

class PunchProfile(NamedTuple):
    choices: int
    threshold: int
    hit_damage: int
    block_damage: int

    pre_msg: str
    hit_msg: str
    blocked_msg: str

    knockout_possible: bool = False

    def is_hit(self):
        return random.randint(1, self.choices) <= self.threshold

@dataclass
class Player:
    name: str
    best: int  # 特长（你的特长拳法会额外造成2点伤害）
    weakness: int  # 弱点（如果对手的招式恰巧为你的弱点，你总是不能闪避）
    is_computer: bool
    punch_profiles: Dict[Literal[1, 2, 3, 4], PunchProfile]
    damage: int = 0
    score: int = 0
    knockout: bool = False
    total_damage: int = 0  # 记录总伤害

    def get_punch_choice(self) -> Literal[1, 2, 3, 4]:
        if self.is_computer:
            return random.randint(1, 4)
        punch = -1
        while punch not in [1, 2, 3, 4]:
            print(f"{self.name}的招式是？")
            punch = int(input())
        return punch

KNOCKOUT_THRESHOLD = 35
KNOCKOUT_COLD = "{loser}被击晕了无法继续进行比赛，胜利属于{winner}"

def get_vulnerability():
    print("他的弱点是？")
    return int(input())

def get_opponent_stats() -> Tuple[int, int]:
    opponent_best = 0
    opponent_weakness = 0
    while opponent_best == opponent_weakness:
        opponent_best = random.randint(1, 4)
        opponent_weakness = random.randint(1, 4)
    return opponent_best, opponent_weakness

def read_punch_profiles(filepath: Path):
    with open(filepath, encoding='utf-8') as f:
        punch_profiles_dict = json.load(f)
    return {
        cast(Literal[1, 2, 3, 4], int(key)): PunchProfile(**value)
        for key, value in punch_profiles_dict.items()
    }

def main() -> None:
    print("拳击游戏")
    print("design by FWY")
    print("由冯炜怡设计创造")
    print("学号")
    print("这个游戏采取奥运规则，三局两胜")

    print("你的对手的名字是？")
    opponent_name = input()

    print("你的名字是？")
    player_name = input()

    print("不同的出拳策略 1 摆拳 2 平勾拳 3上钩拳 4 刺拳")
    print("你擅长的招式是？")
    player_best = int(input())
    player_weakness = get_vulnerability()
    player = Player(
        name=player_name,
        best=player_best,
        weakness=player_weakness,
        is_computer=False,
        punch_profiles=read_punch_profiles(
            Path(__file__).parent / "player-profile.json"
        ),
    )

    opponent_best, opponent_weakness = get_opponent_stats()
    opponent = Player(
        name=opponent_name,
        best=opponent_best,
        weakness=opponent_weakness,
        is_computer=True,
        punch_profiles=read_punch_profiles(
            Path(__file__).parent / "opponent-profile.json"
        ),
    )

    for round_number in (1, 2, 3):
        if player.knockout or opponent.knockout:
            break
        play_round(round_number, player, opponent)

    if player.knockout:
        print(KNOCKOUT_COLD.format(loser=player.name, winner=opponent.name))
    elif opponent.knockout:
        print(KNOCKOUT_COLD.format(loser=opponent.name, winner=player.name))
    elif opponent.score > player.score:
        print(f"{opponent.name}打败了{player.name}")
    else:
        print(f"{player.name}打败了{opponent.name}")

    print("\n\n比赛结束")
    print("感谢游玩")

def is_opponents_turn() -> bool:
    return random.randint(1, 10) > 1

def play_round(round_number: int, player: Player, opponent: Player) -> None:
    print(f"第{round_number}轮次。\n开始....\n")
    if opponent.score >= 2 or player.score >= 2:
        return

    for _action in range(7):
        if _action >= 3:  # 限制连击次数
            break

        if is_opponents_turn():
            punch = opponent.get_punch_choice()
            active = opponent
            passive = player
            opponents_turn = True
        else:
            punch = player.get_punch_choice()
            active = player
            passive = opponent
            opponents_turn = False

        punch_profile = active.punch_profiles[punch]

        if punch == active.best:
            active.damage = active.damage + 2

        print(punch_profile.pre_msg.format(opponent=opponent, player=player))

        if passive.weakness == punch or punch_profile.is_hit():
            print(punch_profile.hit_msg.format(opponent=opponent, player=player))
            if punch_profile.knockout_possible and active.damage > KNOCKOUT_THRESHOLD:
                if opponents_turn and opponent.damage > KNOCKOUT_THRESHOLD:
                    player.knockout = True
                    break
                elif opponents_turn == False and player.damage > KNOCKOUT_THRESHOLD:
                    opponent.knockout = True
                    break
            if opponents_turn:
                opponent.damage = opponent.damage + punch_profile.hit_damage
                active.total_damage += punch_profile.hit_damage  # 记录总伤害
            else:
                player.damage += punch_profile.hit_damage
                active.total_damage += punch_profile.hit_damage
        else:
            print(punch_profile.blocked_msg.format(opponent=opponent, player=player))
            if opponents_turn:
                player.damage += punch_profile.block_damage
                active.total_damage += punch_profile.block_damage
            else:
                opponent.damage += punch_profile.block_damage
                active.total_damage += punch_profile.block_damage

        if player.knockout or opponent.knockout:
            break

    # 恢复抗击打能力
    player.damage = max(0, player.damage - player.total_damage // 2)
    opponent.damage = max(0, opponent.damage - opponent.total_damage // 2)

    # 单独结算每一局的分数
    if player.damage > opponent.damage:
        player.score += 1
        print(f"{player.name}获得了第{round_number}场胜利")
    else:
        opponent.score += 1
        print(f"{opponent.name}获得了第{round_number}场胜利")

if __name__ == "__main__":
    main()
